package cn.uncode.springcloud.starter.security.configuration;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import cn.uncode.springcloud.starter.security.feign.FeignTokenInterceptor;
import cn.uncode.springcloud.starter.security.interceptor.SecurityInterceptor;
import cn.uncode.springcloud.starter.security.jwt.TokenArgumentResolver;
import cn.uncode.springcloud.starter.security.properties.SecurityProperties;
import cn.uncode.springcloud.starter.security.registry.SecurityRegistry;
import feign.RequestInterceptor;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 安全配置类
 * @author juny
 * @date 2019年1月31日
 *
 */
@Order
@Slf4j
@Configuration
@AllArgsConstructor
@ConditionalOnProperty(value = "info.security.enabled", havingValue = "true")
@EnableConfigurationProperties({SecurityProperties.class})
public class SecurityWebAutoConfiguration implements WebMvcConfigurer {
	
	@Autowired
	private SecurityProperties securityProperties;
	
	/**
	 * 认证：token解析
	 */
	@Override
	public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
		argumentResolvers.add(new TokenArgumentResolver());
		log.info("===Uncode-starter===SecurityWebAutoConfiguration===>TokenArgumentResolver registed...");
	}

	/**
	 * 认证：拦截及明名单
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		List<String> list = securityProperties.getWhiteUrlList();
		if(list != null) {
			String[] arr = new String[list.size()];
			for(int i=0;i<list.size();i++) {
				arr[i] = String.valueOf(list.get(i));
			}
			SecurityRegistry.me().excludePathPatterns(arr);
		}
		registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/**")
			.excludePathPatterns(SecurityRegistry.me().getExcludePatterns());
		log.info("===Uncode-starter===SecurityWebAutoConfiguration===>exclude patterns registed...");
	}

	
	/**
	 * token在调用链传递
	 * @return FeignTokenInterceptor
	 */
	@Bean
	@ConditionalOnClass(RequestInterceptor.class)
	public RequestInterceptor requestInterceptor() {
		log.info("===Uncode-starter===SecurityWebAutoConfiguration===>FeignTokenInterceptor inited...");
		return new FeignTokenInterceptor();
	}

}
